package com.chiao.core;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

public abstract class BaseController {
	
	private static final Log log = LogFactory.getLog(BaseController.class);
	private static final String COMMON_ERROR = "500";
	
	@ExceptionHandler({ NoSuchRequestHandlingMethodException.class })
	public ModelAndView handleNotFound(Exception ex, HttpServletRequest request,HttpServletResponse response) {
		String path = request.getPathInfo();
		log.warn("页面未找到: " + path, ex);
		ModelAndView mav = composeModelAndView(path, ex, request, response);
		return mav;
	}

	@ExceptionHandler({ DataAccessException.class })
	public ModelAndView handleDataAccessException(Exception ex, HttpServletRequest request,HttpServletResponse response) {
		String path = request.getPathInfo();
		log.warn("数据访问层出错: " + path, ex);
		ModelAndView mav = composeModelAndView(path, ex, request, response);
		return mav;
	}

	@ExceptionHandler({ Exception.class })
	public ModelAndView handleUncaughtException(Exception ex,HttpServletRequest request,HttpServletResponse response) {
		String path = request.getPathInfo();
		log.warn("未知错误: " + path, ex);
		ModelAndView mav = composeModelAndView(path, ex, request, response);
		return mav;
	}

	private ModelAndView composeModelAndView(String path, Exception ex,HttpServletRequest request,HttpServletResponse response) {
		String accept=request.getHeader("accept");
		String xreq=request.getHeader("X-Requested-With");
		String con="原因："+ClassUtils.getShortName(ex.getClass())+"<br/>"+ex.getMessage();
		String content="{\"errorMsg\":\""+CommonUtils.jsonCharFilter(con)+"\"}";
		
//		String content="{\"errorMsg\":\""+con.replace("\"", "\\\"")+"\"}";
		boolean isJSON=false;
		if(accept.indexOf("application/json")>-1){
			isJSON=true;
		}else{
			if(xreq!=null && xreq.indexOf("XMLHttpRequest")>-1){
				isJSON=true;
			}
		}
		if (isJSON) {
			ajax(content, "text/plain", response);
			return new ModelAndView();
		} else {
			ModelAndView mav = new ModelAndView(COMMON_ERROR);
			mav.addObject("exception", ex.toString());
			mav.addObject("path", path);
			return mav;
		}
	}

	
	public void ajax(String content, String type, HttpServletResponse response) {
		try {
			response.setContentType(type + ";charset=UTF-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.getWriter().write(content);
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
